<template>
  <div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="35%" v-dialog-drag append-to-body>
      <el-form ref="formRef" :model="formData" v-loading="formLoading" label-width="110px">
        <el-form-item label="基站ID" prop="deviceId">
          <el-input v-model="formData.deviceId" placeholder="请输入基站ID" style="width: 200px;margin-right: 20px;"/>
          <el-button type="primary" size="small" @click="viewDeviceRfidList(formData.deviceId)">标签列表</el-button>
        </el-form-item>
        <el-form-item label="标签编码" prop="rfidCode">
          <el-input v-model="formData.rfidCode" placeholder="请输入标签编码" style="width: 200px"/>
        </el-form-item>
        <el-form-item label="亮灯颜色" prop="color">
          <el-select v-model="formData.color" placeholder="请选择亮灯颜色" clearable size="small" style="width: 200px">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.RFID_LIGHT_COLOR)" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="蜂鸣时长" prop="buzzingSeconds">
          <el-input v-model="formData.buzzingSeconds" placeholder="请输入标签编码" style="width: 150px"/>（秒）
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="标签列表" :visible.sync="rfidListDialogVisible" width="50%" v-dialog-drag append-to-body>
      <el-input 
        v-model="rfidCode" 
        placeholder="请输入RFID" 
        style="width: 200px; margin-right: 20px;"
        @clear="rfidCodeQuery"
        @keyup.enter.native="rfidCodeQuery"
        clearable
      />
      <el-button type="primary" size="small" @click="rfidCodeQuery()">搜索</el-button>
      <el-table v-loading="rfidListLoading" :data="filteredRfidList" style="margin-top: 20px;">
        <el-table-column label="标签编码">
          <template slot-scope="scope">
            <span v-if="scope.row && typeof scope.row === 'object' && scope.row.rfidCode">
              {{ scope.row.rfidCode }}
            </span>
            <span v-else>
              {{ scope.row }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import * as DeviceApi from '@/api/hs/device';
import {DICT_TYPE, getDictDatas} from "@/utils/dict";

export default {
  name: "DeviceTest",
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    },
    filteredRfidList() {
      // 使用防抖优化查询性能
      if (!this.rfidCode) {
        return this.rfidList;
      }
      
      const query = this.rfidCode.toLowerCase();
      return this.rfidList.filter(item => {
        // 如果item是对象且有rfidCode属性
        if (item && typeof item === 'object' && item.rfidCode) {
          return item.rfidCode.toLowerCase().includes(query);
        }
        // 如果item是字符串
        if (typeof item === 'string') {
          return item.toLowerCase().includes(query);
        }
        // 其他情况，转换为字符串后匹配
        return String(item).toLowerCase().includes(query);
      });
    }
  },
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        deviceId: undefined,
        rfidCode: undefined,
        color: undefined,
        buzzingSeconds: 3,
      },
      rfidListDialogVisible: false,
      rfidListLoading: false,
      rfidList: [],
      rfidCode: undefined,
      searchTimer: null,
    };
  },
  methods: {
    getDictDatas,
    /** 打开弹窗 */
    async open(deviceId) {
      this.dialogVisible = true;
      this.reset();
      this.dialogTitle = "调试基站";
      this.formData.deviceId = deviceId;
    },
    /** 提交按钮 */
    async submitForm() {
      this.formLoading = true;
      try {
        const data = this.formData;
        await DeviceApi.test(data);
        this.$modal.msgSuccess("指令发送成功");
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        deviceId: undefined,
        rfidCode: undefined,
        color: undefined,
        buzzingSeconds: 3,
      };
      this.resetForm("formRef");
    },
    async viewDeviceRfidList(deviceId) {
      this.rfidListDialogVisible = true;
      this.rfidListLoading = true;
      try {
        const res = await DeviceApi.getDeviceRfidList(deviceId);
        this.rfidList = res.data;
      } finally {
        this.rfidListLoading = false;
      }
    },
    rfidCodeQuery() {
      // 添加防抖功能，避免频繁触发搜索
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        // 强制触发重新计算
        this.$forceUpdate();
      }, 300);
    }
  }
};
</script>
